/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.npmpackagepatch;

import com.inspur.edp.web.npmpackagepatch.packagejson.PackageJsonDependencyInfo;
import com.inspur.edp.web.npmpackagepatch.packagejson.PackageJsonInfo;

import java.util.List;
import java.util.stream.Collectors;

/**
 * package.json 文件操作
 *
 * @author noah
 */
public class PackageJsonFileManager {


    public static PackageJsonInfo read(String path) {
        String packageJsonContent = FileOperation.readAsString(path);
        // 将字符串转换称为实体
        return SerializePackageJson.getInstance().deserialize(packageJsonContent);
    }

    public static void write(PackageJsonInfo packageJsonInfo, String path) {
        String packageJsonInfoContent = SerializePackageJson.getInstance().serialize(packageJsonInfo);
        FileOperation.writeFile(path, packageJsonInfoContent);
    }

    /**
     * 将目标依赖合并到源package.json 中
     *
     * @param sourcePackageJsonInfo
     * @param targetPackageJsonInfo
     */
    public static void merge(PackageJsonInfo sourcePackageJsonInfo, PackageJsonInfo targetPackageJsonInfo) {
        if (sourcePackageJsonInfo == null || targetPackageJsonInfo == null) {
            return;
        }
        // 获取依赖配置
        if (targetPackageJsonInfo.getDependencies() != null && targetPackageJsonInfo.getDependencies().size() > 0) {
            targetPackageJsonInfo.getDependencies().forEach(t -> {
                //
                if (t.getKey() != null && t.getValue() != null) {
                    updatePackageJsonInfoDependency(sourcePackageJsonInfo, t.getKey(), t.getValue(), false);
                }
            });
        }

        // 获取dev 依赖配置
        if (targetPackageJsonInfo.getDevDependencies() != null && targetPackageJsonInfo.getDevDependencies().size() > 0) {
            targetPackageJsonInfo.getDevDependencies().forEach(t -> {
                if (t.getKey() != null && t.getValue() != null) {
                    updatePackageJsonInfoDependency(sourcePackageJsonInfo, t.getKey(), t.getValue(), true);
                }
            });
        }
    }


    /**
     * 更新依赖项
     * @param packageJsonInfo
     * @param key
     * @param value
     * @param isDevDependency
     */
    private static void updatePackageJsonInfoDependency(PackageJsonInfo packageJsonInfo, String key, String value, boolean isDevDependency) {
        List<PackageJsonDependencyInfo> dependencyInfoList = null;
        if (isDevDependency) {
            dependencyInfoList = packageJsonInfo.getDevDependencies();
        } else {
            dependencyInfoList = packageJsonInfo.getDependencies();
        }
        List<PackageJsonDependencyInfo> dependencyInfos = dependencyInfoList.stream().filter(t -> t.getKey().trim().equals(key.trim())).collect(Collectors.toList());
        // 表示不存在
        if (dependencyInfos == null || dependencyInfos.size() == 0) {
            dependencyInfoList.add(new PackageJsonDependencyInfo(key, value));
        } else {
            List<PackageJsonDependencyInfo> finalDependencyInfoList = dependencyInfoList;
            dependencyInfos.forEach(dependencyInfo -> {
                if (dependencyInfo.getKey() != null) {
                    if (dependencyInfo.getKey().trim().equals(key.trim())) {
                        if ("delete".equalsIgnoreCase(value.trim())) {
                            finalDependencyInfoList.remove(dependencyInfo);
                        } else {
                            dependencyInfo.setValue(value);
                        }
                    }
                }
            });
        }
    }

}
